package com.grj.handler;

import com.grj.utils.HttpUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.*;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class FileUploadHandler extends HttpServerHandler {

    private HttpPostRequestDecoder decoder;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        // 检查是否是文件上传
        HttpHeaders headers = request.headers();
        String contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);

        if (contentType != null && contentType.startsWith("multipart/form-data")) {
            handleFileUpload(ctx, request);
        } else {
            super.channelRead0(ctx, request);
        }
    }


    private void handleFileUpload(ChannelHandlerContext ctx, FullHttpRequest request) {
        try {
            // 创建临时目录用于存储上传文件
            File uploadDir = new File("uploads");
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 初始化文件上传解码器
            HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);
            decoder = new HttpPostRequestDecoder(factory, request);

            Map<String, Object> result = new HashMap<>();

            // 处理上传数据
            while (decoder.hasNext()) {
                InterfaceHttpData data = decoder.next();
                if (data != null) {
                    try {
                        if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.FileUpload) {
                            FileUpload fileUpload = (FileUpload) data;
                            if (fileUpload.isCompleted()) {
                                // 保存文件
                                File dest = new File(uploadDir, fileUpload.getFilename());
                                fileUpload.renameTo(dest);

                                result.put("filename", fileUpload.getFilename());
                                result.put("size", fileUpload.length());
                                result.put("savedPath", dest.getAbsolutePath());
                                result.put("status", "success");
                            }
                        }
                    } finally {
                        data.release();
                    }
                }
            }

            String content = HttpUtils.toJson(result);
            FullHttpResponse response = HttpUtils.createResponse(HttpResponseStatus.OK, content, "application/json");
            ctx.writeAndFlush(response);

        } catch (Exception e) {
            String content = "{\"error\": \"文件上传失败: " + e.getMessage() + "\"}";
            FullHttpResponse response = HttpUtils.createResponse(
                    HttpResponseStatus.INTERNAL_SERVER_ERROR, content, "application/json");
            ctx.writeAndFlush(response);
        } finally {
            if (decoder != null) {
                decoder.destroy();
            }
        }
    }


}
